#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>

void Usage(const std::string proc)
{
    std::cout << "\n\rUsage: " << proc << "port[1024+]\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // tcp客户端，不用显式得绑定，系统进行绑定，随机端口
    // 不用绑定了，也就不用listen了，进而不会accepct了
    // 客户端发起cnnect的时候，才进行随机绑定

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_aton(serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int cnt = 5; //允许重连次数
        int isreconnect = false;
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "socket error" << std::endl;
            return 1;
        }
        do
        {
            int n1 = connect(sockfd, (struct sockaddr *)&server, len);
            if (n1 < 0)
            {

                isreconnect = true;
                cnt--;
                std::cerr << "connect error...,reconnect:" << cnt << std::endl;
                // close(sockfd);
                sleep(1); // 如果链接失败，每隔一秒重连一次
                // return 1;
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }

        // while (true) //如果不是常服务，去掉循环
        // {
            std::string message;
            std::cout << "please enter@";
            getline(std::cin, message);
            int re = write(sockfd, message.c_str(), message.size());
            if (re < 0)
            {
                isreconnect = true;
                std::cerr << "write error" << std::endl;
            }

            char inbuff[4096];
            int n2 = read(sockfd, inbuff, sizeof(inbuff));
            if ((n2 > 0))
            {
                inbuff[n2] = 0;
                std::cout << inbuff << std::endl;
            }
            // else{
            //     break;  //如果不是常服务，去掉break
            // }
        //}
        close(sockfd);
    }

    return 0;
}